package org.hq.websocket.sws;

import java.security.Principal;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 用户身份认证
 */
@Component
public class MyInterceptor implements HandshakeInterceptor {

    /**
     * beforeHandshake：在握手之前调用，用于执行用户身份验证和其他初始化操作。如果返回false，则握手被拒绝
     * 用户认证
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("握手开始");
        //获取用户 id 密码
        HttpHeaders he = request.getHeaders();
        //用户 id
        List<String> userid = he.get("userid");
        //用户 密码
        List<String> password = he.get("password");
        // 判断数据是否为空
        if(userid!=null&&password!=null&&Strings.isNotBlank(userid.get(0))&&Strings.isNotBlank(password.get(0))){
            System.out.println(userid.get(0));
            System.out.println(password.get(0));
            // 放入属性域
            attributes.put("userid", userid.get(0));
            return true;
        }

        System.out.println("用户登录已失效");
        return false;
    }

    /**
     * afterHandshake：在握手成功后调用，可以在这里执行一些握手成功后的处理操作
     * 握手后
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("握手完成");
    }

}
